//
//  DetailViewController.m
//  网易公开课项目
//
//  Created by 林 艺 on 13-11-12.
//  Copyright (c) 2013年 Marklin. All rights reserved.
//
//  详细课程视图

#import "DetailViewController.h"
#import "ASIHTTPRequest.h"
#import "UIImageView+WebCache.h"
#import "CourseVideoModel.h"
#import "PlayerVideoViewController.h"
#import "MainViewController.h"
#import "CourseDownloadViewController.h"
#import "BaseNavigationController.h"
#import "LoadCourseDataManager.h"


@interface DetailViewController ()

@end

@implementation DetailViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = @"课程详情";
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentSelected:) name:kContentSelectedNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goOnPlayClicked) name:kGoOnPlayButtonNotification object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
    self.activityView.hidesWhenStopped = YES;
    _currentIndex = 1;
    [self _initNavigationBarItem];
    [self _registerCells];
    _urlString = [NSString stringWithFormat:@"http://so.open.163.com/movie/%@/getMovies4Ipad.htm", self.videoCode];
    NSLog(@"<<<<<<%@", _urlString);
    [self.activityView startAnimating];
    [dataManager loadDetailCourseDataWith:_urlString];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadDetailCourseDone:) name:kDetailCourseNotification object:nil];
    [self _initBlackAlertView];

    
}



- (void)_initBlackAlertView
{
    _blackAlertView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 140)];
    _blackAlertView.backgroundColor = [UIColor blackColor];
    _blackAlertView.layer.cornerRadius = 10;
    _blackAlertView.center = CGPointMake(160, 160);
    _blackAlertView.alpha = 0.8;
    
    UIImageView *checkMark = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 37, 37)];
    checkMark.backgroundColor = [UIColor clearColor];
    checkMark.image = [UIImage imageNamed:@"37x-Checkmark.png"];
    checkMark.center = CGPointMake(160/2, 140/2);
    [_blackAlertView addSubview:checkMark];
    
    _bookmarkLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
    _bookmarkLabel.center = CGPointMake(160/2, 140*3/4);
    _bookmarkLabel.backgroundColor = [UIColor clearColor];
    _bookmarkLabel.textColor = [UIColor whiteColor];
    _bookmarkLabel.font = [UIFont systemFontOfSize:15];
    _bookmarkLabel.textAlignment = NSTextAlignmentCenter;
    [_blackAlertView addSubview:_bookmarkLabel];
    
}

- (void)_registerCells
{
    [self.tableView registerNib:[UINib nibWithNibName:@"DetailBigCell" bundle:nil] forCellReuseIdentifier:@"DetailBigCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SynopsisCell" bundle:nil] forCellReuseIdentifier:@"SynopsisCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RelationCell" bundle:nil] forCellReuseIdentifier:@"RelationCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MiddleCell" bundle:nil] forCellReuseIdentifier:@"MiddleCell"];
}

- (void)_initRelationCourse
{
    LoadCourseDataManager *dataManger = [LoadCourseDataManager shareInstance];
    NSArray *tagsArr = [_model.tags componentsSeparatedByString:@","];
    for (CourseModel *model in dataManger.courseData)
    {
        
        NSArray *tempTagsArr = [model.tags componentsSeparatedByString:@","];
        NSString *tempMark = nil;
        for (NSString *str in tempTagsArr)
        {
            for (NSString *subStr in tagsArr)
            {
                if ([str isEqualToString:subStr] && ![model.title isEqualToString:_model.title])
                {
                    tempMark = subStr;
                }
            }
        }//for (NSString *str in tempTagsArr)
        if (tempMark != nil)
        {
            if (_relationCourseArray == nil)
            {
                _relationCourseArray = [[NSMutableArray alloc] init];
            }
            [_relationCourseArray addObject:model];
        }
    }//for (CourseModel *model in dele.courseData)
}

- (void)_initNavigationBarItem
{
    //返回
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setBackgroundImage:[UIImage imageNamed:@"btn_left.png"] forState:UIControlStateNormal];

    [back setTitle:@"返回" forState:UIControlStateNormal];
    back.titleLabel.font = [UIFont systemFontOfSize:11];
    [back addTarget:self action:@selector(backClicked) forControlEvents:UIControlEventTouchUpInside];
    back.frame = CGRectMake(0, 0, 50, 34);
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = leftButton;
    
    //搜索条
    UIButton *corect = [UIButton buttonWithType:UIButtonTypeCustom];
    [corect setBackgroundImage:[UIImage imageNamed:@"btn_right.png"] forState:UIControlStateNormal];
    
    [corect setTitle:@"纠错" forState:UIControlStateNormal];
    corect.titleLabel.font = [UIFont systemFontOfSize:11];
    
    corect.frame = CGRectMake(0, 0, 50, 34);
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:corect];
    self.navigationItem.rightBarButtonItem = rightButton;

}

- (void)groupCourseVideoArray
{
    if (_translatedArray == nil)
    {
        _translatedArray = [[NSMutableArray alloc] init];
    }
    if (_untranslatedArray == nil)
    {
        _untranslatedArray = [[NSMutableArray alloc] init];
    }
    for (CourseVideoModel *model in _model.videoList)
    {
        if ([model.subtitleLanguage isEqualToString:@"无字幕"])
        {
            [_untranslatedArray addObject:model];
        }
        else
        {
            [_translatedArray addObject:model];
        }
    }
}

#pragma mark --
#pragma mark 课时view的创建
- (void)initCellView
{
    [self groupCourseVideoArray];
    _cellView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];
    _cellView.backgroundColor = [UIColor clearColor];
    UILabel *headLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 150, 20)];
    headLabel.font = [UIFont systemFontOfSize:15];
    headLabel.textColor = [UIColor brownColor];
    headLabel.backgroundColor = [UIColor clearColor];
    headLabel.text = @"已翻译";
    [_cellView addSubview:headLabel];
    
    _lessionHeight += 40;
    _listButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _listButton.frame = CGRectMake(200, 10, 49, 20);
    [_listButton setImage:[UIImage imageNamed:@"lesson_list_btn.png"] forState:UIControlStateNormal];
    [_listButton setImage:[UIImage imageNamed:@"lesson_list_btn_select.png"] forState:UIControlStateDisabled];
    _listButton.tag = ListButtonTag;
    [_listButton addTarget:self action:@selector(cellButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_cellView addSubview:_listButton];
    _listLabel = [[UILabel alloc] initWithFrame:CGRectMake(218, 10, 24, 18)];
    _listLabel.text = @"列表";
    _listLabel.font = [UIFont systemFontOfSize:12];
    _listLabel.textColor = [UIColor whiteColor];
    _listLabel.backgroundColor = [UIColor clearColor];
    [_cellView addSubview:_listLabel];
    
    _postButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _postButton.frame = CGRectMake(200+49, 10, 49, 20);
    _postButton.enabled = NO;
    [_postButton setImage:[UIImage imageNamed:@"lesson_post_btn.png"] forState:UIControlStateNormal];
    [_postButton setImage:[UIImage imageNamed:@"lesson_post_btn_select.png"] forState:UIControlStateDisabled];
    _postButton.tag = ListButtonTag+1;
    [_postButton addTarget:self action:@selector(cellButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_cellView addSubview:_postButton];
    _postLabel = [[UILabel alloc] initWithFrame:CGRectMake(267, 10, 24, 18)];
    _postLabel.text = @"矩阵";
    _postLabel.font = [UIFont systemFontOfSize:12];
    _postLabel.textColor = [UIColor brownColor];
    _postLabel.backgroundColor = [UIColor clearColor];
    [_cellView addSubview:_postLabel];
    _lessionButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 40, 320, 100)];
    _lessionButtonView.backgroundColor = [UIColor clearColor];
    [_cellView addSubview:_lessionButtonView];
    
    [self  postButtonView];
}

- (void)postButtonView
{
    _lessionHeight = 30+10;
    //添加翻译按钮
    for (int i = 0; i < _translatedArray.count; i++)
    {
        //中断循环标志位
        BOOL flag = NO;
        for (int j = 0; j < 3; j++)
        {
            int temp = i*3+j;
            
            CourseVideoModel *model = (CourseVideoModel *)[_translatedArray objectAtIndex:temp];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button addTarget:self action:@selector(lessionTranslatedClicked:) forControlEvents:UIControlEventTouchUpInside];
            button.frame = CGRectMake(10+100*j, (45+5)*i, 99, 45);
            button.tag = kLessionTranslatedTag+temp;
            NSLog(@">>>>>%f", model.lastPlayTime);
            
            [button setBackgroundImage:[UIImage imageNamed:@"course_btn.png"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"course_btn_active.png"] forState:UIControlStateHighlighted];
            
            if (model.isDownloaded || model.isDownloading || model.isSelectedToDownload)
            {
                [button setTitle:[NSString stringWithFormat:@"第%@课 已下", model.pnumber] forState:UIControlStateNormal];
            }
            else
            {
                [button setTitle:[NSString stringWithFormat:@"第%@课", model.pnumber] forState:UIControlStateNormal];
            }
            button.titleLabel.font = [UIFont systemFontOfSize:15];
            [_lessionButtonView addSubview:button];
            
            if (temp >= _translatedArray.count-1)
            {
                flag = YES;
                break;
            }
        }//for (int j = 0; j < 3; j++)
        _lessionHeight += 50;
        if (flag)
        {
            break;
        }
    }//for (int i = 0; i <= _translatedArray.count/3; i++)
    
    if (_untranslatedArray.count == 0)
    {
        UILabel *footLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, _lessionHeight-40+5, 150, 20)];
        footLabel.font = [UIFont systemFontOfSize:15];
        footLabel.textColor = [UIColor brownColor];
        footLabel.tag = 38;
        footLabel.backgroundColor = [UIColor clearColor];
        footLabel.text = @"全部翻译完成";
        [_lessionButtonView addSubview:footLabel];
        _lessionHeight += 35;
    }
    else
    {
        UILabel *footLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, _lessionHeight-40+5, 150, 20)];
        footLabel.font = [UIFont systemFontOfSize:15];
        footLabel.textColor = [UIColor brownColor];
        footLabel.tag = 38;
        footLabel.backgroundColor = [UIColor clearColor];
        footLabel.text = @"未翻译";
        [_lessionButtonView addSubview:footLabel];
        _lessionHeight += 35;
        CGFloat tempHeight = _lessionHeight;
        //添加未翻译按钮
        for (int i = 0; i < _untranslatedArray.count; i++)
        {
            //中断循环标志位
            BOOL flag = NO;
            for (int j = 0; j < 3; j++)
            {
                int temp = i*3+j;
                
                CourseVideoModel *model = (CourseVideoModel *)[_untranslatedArray objectAtIndex:temp];
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                [button setBackgroundImage:[UIImage imageNamed:@"course_btn.png"] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"course_btn_active.png"] forState:UIControlStateHighlighted];
                [button addTarget:self action:@selector(lessionUntranslatedClicked:) forControlEvents:UIControlEventTouchUpInside];
                button.frame = CGRectMake(10+100*j, tempHeight-40+(45+5)*i, 99, 45);
                button.tag = kLessionUntranslatedTag+temp;
                [button setTitle:[NSString stringWithFormat:@"第%@课", model.pnumber] forState:UIControlStateNormal];
                [_lessionButtonView addSubview:button];
                
                if (temp >= _untranslatedArray.count-1)
                {
                    flag = YES;
                    break;
                }
            }//for (int j = 0; j < 3; j++)
            _lessionHeight += 50;
            if (flag)
            {
                break;
            }
        }//for (int i = 0; i < _translatedArray.count/3; i++)
    }
    _lessionButtonView.frame = CGRectMake(_lessionButtonView.frame.origin.x, _lessionButtonView.frame.origin.y, _lessionButtonView.frame.size.width, _lessionHeight-40);

    
}

- (void)lessionTranslatedClicked:(UIButton *)button
{
    CourseVideoModel *model = (CourseVideoModel *)[_translatedArray objectAtIndex:button.tag-kLessionTranslatedTag];

    [self presentVideoByCourseModel:model];
}

- (void)listButtonView
{
    _lessionHeight = 30+10;
    //添加翻译按钮
    for (int i = 0; i < _translatedArray.count; i++)
    {
        CourseVideoModel *model = (CourseVideoModel *)[_translatedArray objectAtIndex:i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setBackgroundImage:[UIImage imageNamed:@"course1.png"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"course1_active.png"] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(lessionTranslatedClicked:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(10, (40+5)*i, 305, 40);
        button.tag = kLessionTranslatedTag+i;
        
        [button setTitle:[NSString stringWithFormat:@"【第%@课】%@", model.pnumber, model.title] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:13];
        button.titleLabel.textAlignment = NSTextAlignmentLeft;
        [_lessionButtonView addSubview:button];
        
        _lessionHeight += 45;
    }//for (int i = 0; i <= _translatedArray.count; i++)
    
    if (_untranslatedArray.count == 0)
    {
        UILabel *footLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, _lessionHeight-40+5, 150, 20)];
        footLabel.font = [UIFont systemFontOfSize:15];
        footLabel.textColor = [UIColor brownColor];
        footLabel.backgroundColor = [UIColor clearColor];
        footLabel.text = @"全部翻译完成";
        [_lessionButtonView addSubview:footLabel];
        _lessionHeight += 35;
    }
    else
    {
        UILabel *footLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, _lessionHeight-40+5, 150, 20)];
        footLabel.font = [UIFont systemFontOfSize:15];
        footLabel.textColor = [UIColor brownColor];
        footLabel.backgroundColor = [UIColor clearColor];
        footLabel.text = @"未翻译";
        [_lessionButtonView addSubview:footLabel];
        _lessionHeight += 35;
        CGFloat tempHeight = _lessionHeight;
        //添加未翻译按钮
        for (int i = 0; i < _untranslatedArray.count; i++)
        {
            CourseVideoModel *model = (CourseVideoModel *)[_untranslatedArray objectAtIndex:i];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setBackgroundImage:[UIImage imageNamed:@"course1.png"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"course1_active.png"] forState:UIControlStateHighlighted];
            [button addTarget:self action:@selector(lessionUntranslatedClicked:) forControlEvents:UIControlEventTouchUpInside];
            button.frame = CGRectMake(10, tempHeight-40+(40+5)*i, 305, 40);
            button.tag = kLessionUntranslatedTag+i;
            [button setTitle:[NSString stringWithFormat:@"【第%@课】%@", model.pnumber, model.title] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:13];
            button.titleLabel.textAlignment = NSTextAlignmentLeft;
            [_lessionButtonView addSubview:button];
            _lessionHeight += 45;
        }//for (int i = 0; i <= _translatedArray.count; i++)
    }
    
    _lessionButtonView.frame = CGRectMake(_lessionButtonView.frame.origin.x, _lessionButtonView.frame.origin.y, _lessionButtonView.frame.size.width, _lessionHeight-40);
    _cellView.frame = CGRectMake(_cellView.frame.origin.x, _cellView.frame.origin.y, _cellView.frame.size.width, _lessionHeight-40);
}

- (void)lessionUntranslatedClicked:(UIButton *)button
{
    CourseVideoModel *model = (CourseVideoModel *)[_untranslatedArray objectAtIndex:button.tag-kLessionUntranslatedTag];
//    NSLog(@"%@", model.repovideourlmp4);
//    NSLog(@"%@", model.pnumber);
    [self presentVideoByCourseModel:model];
}

- (void)presentVideoByCourseModel:(CourseVideoModel *)videoModel
{
    PlayerVideoViewController *player = [[PlayerVideoViewController alloc] initWithNibName:@"PlayerVideoViewController" bundle:nil withPlayType:PlayWithURL];
    NSLog(@"%@", videoModel.localPlayPath);
    player.courseModel = _model;
    player.videoModel = videoModel;
    [self presentViewController:player animated:YES completion:nil];
}

#pragma mark -- 
#pragma mark 收藏按钮功能

- (void)cancelBookmark
{
    LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
    NSMutableArray *dataModels = [NSMutableArray arrayWithArray:[dataManager loadBookmarkData]];
    NSInteger index = 0;
    for (int i = 0; i < dataModels.count; i++)
    {
        CourseModel *model = dataModels[i];
        if (model.title == _model.title)
        {
            index = i;
            break;
        }
    }
    [dataModels removeObjectAtIndex:index];
    [dataManager writeDataToBookmarkArchiverWithArray:dataModels];

}


- (void)modelIsBookmarked
{
    LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
    NSArray *dataModels = [NSMutableArray arrayWithArray:[dataManager loadBookmarkData]];
    for (CourseModel *model in dataModels)
    {
        if ([model.title isEqualToString:_model.title])
        {
            _model.isBookmark = YES;
            [self.bookmarkButton setImage:[UIImage imageNamed:@"mark_course_ico.png"] forState:UIControlStateNormal];
        }
    }

}

- (void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark --
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 1;
    }
    else
    {
        if (_currentIndex == 0)
        {
            return 1;
        }
        else if (_currentIndex == 1)
        {
            return 1;
        }
        else if (_currentIndex == 2)
        {
            return _relationCourseArray.count;
        }
        else
        {
            return 0;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        DetailBigCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailBigCell"];
        [cell.courseImageView setImageWithURL:[NSURL URLWithString:_model.imagePath]];
        cell.titleLabel.text = _model.title;
        if (_model.lastPlayPnumber == nil)
        {
            cell.lastPlayTimeLabel.text = @"未观看";
        }
        else
        {
            if (_model.lastPlaySeconds < 60)
            {
                cell.lastPlayTimeLabel.text = [NSString stringWithFormat:@"看到: 第%@课少于1分钟", _model.lastPlayPnumber];
            }
            else
            {
                cell.lastPlayTimeLabel.text = [NSString stringWithFormat:@"看到: 第%@课 %02d:%02d", _model.lastPlayPnumber, _model.lastPlaySeconds/60, _model.lastPlaySeconds%60];
            }
            
        }
        return cell;
    }
    else
    {
        switch (_currentIndex) {
            case 0:
            {
                SynopsisCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SynopsisCell"];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.tagsLabel.text = _model.tags;
                cell.schoolLabel.text = _model.school;
                cell.directerLabel.text = _model.director;
                cell.descriptionLabel.frame = CGRectMake(cell.descriptionLabel.frame.origin.x, cell.descriptionLabel.frame.origin.y, _contentSize.width, _contentSize.height);
                
                cell.descriptionLabel.text = _model.description;
                return cell;
            }
                break;
            case 1:
            {
                MiddleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MiddleCell"];
                cell.selected = YES;
                [cell.cellView addSubview:_cellView];
                cell.cellView.frame = CGRectMake(cell.cellView.frame.origin.x, cell.cellView.frame.origin.y, cell.cellView.frame.size.width, _lessionHeight);
                return cell;
            }
                break;
            case 2:
            {
                RelationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RelationCell"];
                CourseModel *model = (CourseModel *)_relationCourseArray[indexPath.row];
                [cell.courseImageView setImageWithURL:[NSURL URLWithString:model.imagePath]];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.titleLabel.text = model.title;
                cell.tagsLabel.text = model.tags;
                cell.playCountLabel.text = [NSString stringWithFormat:@"%@", model.playcount];
                cell.updatePlayCountLabel.text = [NSString stringWithFormat:@"%@", model.updatedPlaycount];
                
                return cell;
            }
                break;
            default:
                return nil;
                break;
        }
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return 140;
    }
    else
    {
        if (_currentIndex == 0)
        {
            return 125+_contentSize.height;
        }
        else if (_currentIndex == 1)
        {
            _cellView.frame = CGRectMake(_cellView.frame.origin.x, _cellView.frame.origin.y, _cellView.frame.size.width, _lessionHeight);
            return _lessionHeight;
        }
        else if (_currentIndex == 2)
        {
            return 90;
        }
        else
        {
            return 0;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && _currentIndex == 2)
    {
        DetailViewController *detailController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
        CourseModel *model = [_relationCourseArray objectAtIndex:indexPath.row];
        detailController.videoCode = model.plid;
        

        [self.navigationController pushViewController:detailController animated:YES];
    }
}

- (void)cellButtonClicked:(UIButton *)button
{
    if (button.tag == ListButtonTag)
    {
        _listButton.enabled = NO;
        _listLabel.textColor = [UIColor brownColor];
        
        _postButton.enabled = YES;
        _postLabel.textColor = [UIColor whiteColor];
        [self cleanUpLessionButtonView];
        [self listButtonView];
        [_tableView reloadData];
        
    }
    else
    {
        _listButton.enabled = YES;
        _listLabel.textColor = [UIColor whiteColor];
        
        _postButton.enabled = NO;
        _postLabel.textColor = [UIColor brownColor];
        [self cleanUpLessionButtonView];
        [self postButtonView];
        [_tableView reloadData];
    }
}

- (void)cleanUpLessionButtonView
{
    for (UIView *view in _lessionButtonView.subviews)
    {
        [view removeFromSuperview];
    }
}

#pragma mark --
#pragma mark NSNotificationCenter
- (void)contentSelected:(NSNotification *)note
{
    NSString *index = (NSString *)note.object;
    _currentIndex = [index integerValue];
    [_tableView reloadData];
}

- (void)loadDetailCourseDone:(NSNotification *)note
{
    CourseModel *model = note.object;
    LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
    /***************   *******************/
    NSArray *readModels = [dataManager loadDownloadData];
    BOOL flag = YES;
    for (CourseModel *tempModel in readModels)
    {
        if ([tempModel.title isEqualToString:model.title])
        {
            _model = tempModel;
            flag = NO;
        }
    }
    if (flag)
    {
        _model = model;
    }
//    历史记录BUG点
#if 0
    NSArray *historyModels = [dataManager loadHistoryData];
    for (CourseModel *historyModel in readModels)
    {
        if ([historyModel.title isEqualToString:model.title])
        {
            _model.lastPlayPnumber = historyModel.lastPlayPnumber;
            _model.lastPlaySeconds = historyModel.lastPlaySeconds;
            _model.lastPlayTime = historyModel.lastPlayTime;
            for (CourseVideoModel * in <#collection#>) {
                <#statements#>
            }
        }
    }
#endif
    
    _contentSize = [_model.description sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(250, 2000)];
    
    [self initCellView];
    [self modelIsBookmarked];
    [self _initRelationCourse];
    [self.tableView reloadData];
    [self.activityView stopAnimating];
    self.woodBackground.hidden = NO;
    self.tableView.hidden = NO;
    self.courseBottomBar.hidden = NO;

    
    
}

#pragma mark --
#pragma mark CourseBottomBarButtonClicked
- (IBAction)bookmarkClicked:(UIButton *)sender
{
    LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
    if (_model.isBookmark)
    {
        _model.isBookmark = NO;
        [self cancelBookmark];
        
        [self.view addSubview:_blackAlertView];
        _blackAlertView.hidden = NO;
        _blackAlertView.alpha = 0.8;
        _bookmarkLabel.text = @"已取消收藏";
        [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(blackAlertViewDismiss) userInfo:nil repeats:NO];
        
        [sender setImage:[UIImage imageNamed:@"cancelmark_course_ico.png"] forState:UIControlStateNormal];
    }
    else
    {
      
        _model.isBookmark = YES;
        [dataManager writeDataToBookmarkArchiverWithModel:_model];
        
        [self.view addSubview:_blackAlertView];
        _blackAlertView.hidden = NO;
        _blackAlertView.alpha = 0.8;
        _bookmarkLabel.text = @"添加收藏成功";
        [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(blackAlertViewDismiss) userInfo:nil repeats:NO];
        
        [sender setImage:[UIImage imageNamed:@"mark_course_ico.png"] forState:UIControlStateNormal];
    }
}

- (void)blackAlertViewDismiss
{
    [UIView animateWithDuration:1.5 animations:^{
        _blackAlertView.alpha = 0;
        _blackAlertView.hidden = YES;
    }];
}

- (IBAction)shareClicked:(UIButton *)sender
{
    
}

- (IBAction)downClicked:(UIButton *)sender
{
    CourseDownloadViewController *downloadControl = [[CourseDownloadViewController alloc] initWithNibName:@"CourseDownloadViewController" bundle:nil];
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:downloadControl];
    downloadControl.translatedArray = _translatedArray;
    downloadControl.untranslatedArray = _untranslatedArray;
    downloadControl.courseModel = _model;
    [self presentViewController:nav animated:YES completion:nil];
}

- (IBAction)commentClicked:(UIButton *)sender
{
    
}

- (void)goOnPlayClicked
{
    PlayerVideoViewController *player = [[PlayerVideoViewController alloc] initWithNibName:@"PlayerVideoViewController" bundle:nil];
    
    for (CourseVideoModel *videoModel in _model.videoList)
    {
        if (_model.lastPlayPnumber == nil)
        {
            _model.lastPlayPnumber = [[NSNumber alloc] initWithInt:1];
        }
        NSLog(@"%@", _model.lastPlayPnumber);
        if ([videoModel.pnumber isEqualToNumber:_model.lastPlayPnumber])
        {
            player.videoModel = videoModel;

        }
    }
    player.courseModel = _model;
    [self presentViewController:player animated:YES completion:nil];
}

#pragma mark --
#pragma mark viewWillAppear
-(void)viewWillAppear:(BOOL)animated
{
    //设置全屏
    UIView *tabbarContentView = [self.tabBarController valueForKey:@"viewControllerTransitionView"];
    tabbarContentView.frame = CGRectMake(0, 0, 320, 480);
    NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (NSUInteger)supportedInterfaceOrientations
{
    
    return UIInterfaceOrientationMaskPortrait;
    
}





@end
